package example.tallydemo.MyFragment;


import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import example.tallydemo.MyActivity.ShowDetailActivity;
import example.tallydemo.MyAdapter.MyListAdapter;
import example.tallydemo.MyContextMeau.TzhContextMenu;
import example.tallydemo.MyEntity.AccountBook;
import example.tallydemo.MyEntity.AccountManager;
import example.tallydemo.MyTools.MyTimeTool;
import example.tallydemo.R;

/**
 * A simple {@link Fragment} subclass.
 */
public class MainFragment extends MyBaseFragment
{

    View view;
    AccountManager accountManager = null;
    MyListAdapter myListAdapter;
    ListView listView;
    MyTimeTool myTimeTool;

    int year;
    int month;
    List<AccountBook> inputBooks = new ArrayList<>();
    List<AccountBook> expendBooks = new ArrayList<>();

    double money;
    double account = 0;
    double total_input = 0;
    double total_expend = 0;
    double total_mouth_input = 0;
    double total_mouth_expend = 0;



    public MainFragment()
    {
        // Required empty public constructor
    }

    // 加载配置
    public void loadConfig()
    {
        SharedPreferences sharedPref = getActivity()
                .getSharedPreferences("set", Context.MODE_PRIVATE); //可以在多个Acitivy里访问的首选项
        money = Double.valueOf(sharedPref.getString("money","20"));
    }


    public void setFragment(AccountManager accountManager)
    {
        this.accountManager = accountManager;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState)
    {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_main, container, false);
        this.view = view;
        loadConfig();
        onCreate(view);
        setAccountShow(view);
        return view;
    }

    public void onCreate(View view)
    {
        myTimeTool = new MyTimeTool();
        myTimeTool.setTody();
        year = myTimeTool.getYear();
        month = myTimeTool.getMonth();
        myListAdapter = new MyListAdapter(getContext());
        listView = view.findViewById(R.id.id_main_listview);
        listView.setAdapter(myListAdapter);

        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener()
        {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id)
            {
                AccountBook it = (AccountBook) myListAdapter.getItem(position);
                onItemLongClicked(view,it);
                return false;
            }
        });


        myListAdapter.addBooks(accountManager.queryMouth(year,month));

    }

    public void onDetailItem(View view,AccountBook it)
    {
        Intent intent = new Intent(getContext(), ShowDetailActivity.class);

        if (it.getType())
        {
            intent.putExtra("type","收入");
        }
        else
        {
            intent.putExtra("type","支出");
        }
        intent.putExtra("id",it.getId());
        intent.putExtra("origin",it.getOrigin());
        intent.putExtra("classify",it.getClassify());
        intent.putExtra("money",String.valueOf(it.getMoney()));
        intent.putExtra("date",myTimeTool.DateToString(it.getDate()));
        intent.putExtra("introduction",it.getIntroduction());
        startActivity(intent);
    }

    private void onItemLongClicked(final View view, final AccountBook book)
    {
        TzhContextMenu contextMenu = new TzhContextMenu();
        contextMenu.addContextItem("删除", "remove");
        contextMenu.addContextItem("详细", "detail");

        contextMenu.show(getContext(),view,view.getWidth()/2,-view.getHeight()/2);//显示位置
        contextMenu.listener = new TzhContextMenu.OnContextMenuItemClickedListener()
        {
            @Override
            public void onContextMenuItemClicked(String option, String value)
            {
                if (value.equals("remove"))
                {
                    onDelItem(view,book);
                }else if (value.equals("detail"))
                {
                    onDetailItem(view,book);
                }
            }
        };
    }

    public void onDelItem(View view1,AccountBook it)
    {
        accountManager.delete(it);
        myListAdapter.delAll();
        myListAdapter.addBooks(accountManager.queryMouth(year,month));
        setAccountShow(view);
        myListAdapter.notifyDataSetChanged();
    }


    public void update()
    {
        if (myListAdapter != null)
        {
            myListAdapter.delAll();
            myListAdapter.addBooks(accountManager.queryMouth(year,month));
            myListAdapter.notifyDataSetChanged();
            setAccountShow(view);
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        update();
    }


    public void setAccountShow(View view)
    {
        inputBooks.clear();
        expendBooks.clear();

        account = 0;
        total_mouth_input = 0;
        total_mouth_expend = 0;
        total_input = 0;
        total_expend = 0;

        if (accountManager.queryMouth(year,month).size() != 0)
        {
            for (AccountBook it:accountManager.queryMouth(year,month))
            {
                if (it.getType())
                {
                    inputBooks.add(it);
                    total_mouth_input += it.getMoney();
                }
                else
                {
                    expendBooks.add(it);
                    total_mouth_expend += it.getMoney();
                }
            }
        }

        for (AccountBook it:accountManager.query())
        {
            if (it.getType())
            {
                inputBooks.add(it);
                total_input += it.getMoney();
            }
            else
            {
                expendBooks.add(it);
                total_expend += it.getMoney();
            }
        }
        account = money + total_input - total_expend;
        ((TextView)view.findViewById(R.id.id_main_account)).setText(String.valueOf(account));
        ((TextView)view.findViewById(R.id.id_main_input)).setText(String.valueOf(total_mouth_input));
        ((TextView)view.findViewById(R.id.id_main_expend)).setText(String.valueOf(total_mouth_expend));

    }

    @Override
    public void setUserVisibleHint(boolean hidden)
    {
        // TODO Auto-generated method stub
        super.setUserVisibleHint(hidden);
        if (hidden)
        {
            update();
        }
    }


}
